<?php
/**
 * Created by PhpStorm.
 * User: sunbo
 * Date: 2019/7/3
 * Time: 6:37 PM
 */
namespace app\index\controller;
use think\Exception;
class Blockchain extends CoinBaseContorller
{
     ///获取BTC USDT地址
    public function Get_BTC_USDT_Address($mobile){
        $logn=new CitPayApi();
         $result= $logn->getRechargeAddress($mobile);
        return $result->address;
    }


    //更新 轮询查看 代币转出状态
    public function  Up_CustomCoin(){
        try{
            $row= $this->db_select("select a.guid,a.transaction_id from token_bill_transaction_coin a INNER JOIN token_sys_coin b on a.token_sys_coin_guid=b.guid and b.iscustom=1 where a.type=1 and a.transaction_id <> '' and a.status<>1");
            for ($x=0;$x<count($row);$x++){
                $txid=$row[$x]["transaction_id"];
                $guid=$row[$x]["guid"];
                if($this->set_Coin_Txit_Status($txid)){
                    $this->db_exec(array("update token_bill_transaction_coin set status=1 where guid='".$guid."'"));
                }
            }
        }catch (Exception $e){

        }
    }

    //  params: {"sender": "", "receiver":"", "amount":100000000}
    public  function  Sender($sender,$receiver,$amount){
        $url= $this->Get_Custom_Coin_Url()."/api/sender";
        $data=array("sender"=>$sender,"receiver"=>$receiver,"amount"=>$amount);
        $data= $this->post_json_data($url,"");
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        return $result->data->sender;
    }


  public  function set_Coin_Txit_Status($txid){
        if(strlen($txid)==0)
        {
            return;
        }
        $url= $this->Get_Custom_Coin_Url()."/api/txStatus";
        $data=array("txid"=>$txid);
        $data= $this->post_json_data($url,json_encode($data));
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        return $result->data->txStatus;
    }

    ///发送代币交易  22200070c1c17f50040780991a7d47faa31bdedf0806ff711f5eded2e073bb7e
    public function Send_CustomCoin($transaction_guid){
        $row=$this->db_select("select sellout_address,tokencount,purchasein_address from token_bill_transaction_coin where guid='".$transaction_guid."'");
        if(count($row)==0){
            exception ("当前交易不存在");
            return;
        }

        $url= $this->Get_Custom_Coin_Url()."/api/createTx";
        $data=array("sender"=>$row[0]["sellout_address"],"receiver"=>$row[0]["purchasein_address"],"amount"=>$row[0]["tokencount"]);
        $data= $this->post_json_data($url,json_encode($data));
        $this->log("交易发送返回信息:".$data["result"]);
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        $txid= $result->data->txid;
        $this->db_exec(array("update token_bill_transaction_coin set transaction_id='".$txid."',status=1 where guid='".$transaction_guid."'"));
    }


    ///获取代币高度
    public  function  Get_Custom_Coin_Height(){
        $url= $this->Get_Custom_Coin_Url()."/api/height";
        $data= $this->post_json_data($url,"");
        $this->log("代币返回信息:".$data["result"]);
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        return $result->data->height;
    }

    ///获取代币地址
    public  function  Get_Custom_Coin_Address(){
        $url= $this->Get_Custom_Coin_Url()."/api/generateAddress";
        $data= $this->post_json_data($url,"");
        $this->log("代币返回信息:".$data["result"]);
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        return $result->data->address;
    }

    public function checkCustom_Coin($data){
        if($data["code"]!=200){
            exception ("代币服务器发生错误");
        }
        $result=json_decode($data["result"]);

        if($result->code!=200){
            exception ($result->message);
        }
        return "";
    }

    public function Get_Custom_Coin_Url(){
        $row=$this->db_select("select value from token_sys_config where guid='7'");
        $url= $row[0]["value"];
        return $url;
    }

    /*
      * post 发送JSON 格式数据
     * @param $url string URL
      * @param $data_string string 请求的具体内容
     * @return array
     *      code 状态码
     *      result 返回结果
     */
     function post_json_data($url, $data_string) {
         $this->log("代币接口和数据  URL:".$url." data:".$data_string);
             //初始化
         $ch = curl_init();
        //设置post方式提交
        curl_setopt($ch, CURLOPT_POST, 1);
        //设置抓取的url
         curl_setopt($ch, CURLOPT_URL, $url);
        //设置post数据
         curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
         //设置头文件的信息作为数据流输出
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=utf-8','Content-Length:'.strlen($data_string)));
        ob_start();
        //执行命令
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      return array('code'=>$return_code, 'result'=>$return_content);
    }

    ///返回代币单价
    public function Get_Custom_Coin_Price(){
        return 0;
    }

    //返回BTC单价
    public function Get_BTC_Price(){
        return 0;
    }

    //返回USDT单价
    public function Get_USDT_Price(){
        return 0;
    }

    /*
     * 代币扫块，新增到交易列表
    */
    public  function  InsertCustomCoin($output){
        $erroraddress="";
        $error_latest_block_heigh=-1;
        try{
            $row=$this->db_select("select a.token_sys_user_guid,a.address,a.latest_block_height from token_user_coin_address a INNER JOIN token_sys_coin b on b.guid=a.token_sys_coin_guid WHERE b.iscustom=1");
            for($x=0;$x<count($row);$x++){
                $erroraddress=$address=$row[$x]["address"];
               $token_sys_user_guid=$row[$x]["token_sys_user_guid"];
                $error_latest_block_heigh=$latest_block_height=$row[$x]["latest_block_height"];
               $tx_list=$this->get_txlist($address,$latest_block_height);
               if(count($tx_list)>0){
                 $this->insert_sys_bill($tx_list,$token_sys_user_guid);
               }
            }
            return "扫块完成";
        }catch (Exception $e){
            $output->writeln("扫块错误:".$erroraddress." height:".$error_latest_block_heigh);
            return $e->getMessage();
        }
    }

    public function usortTest($a, $b) {
        if($a->height==$b->height) return 0;
        return ($a->height<$b->height)?-1:1;
    }

    public function get_txlist($address,$height){
        $url= $this->Get_Custom_Coin_Url()."/api/txList";
        $data=array("address"=>$address,"height"=>$height);
        $data= $this->post_json_data($url,json_encode($data));
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        $a=$result->data->txList;
        usort($a, array($this, 'usortTest'));
        return $a;
    }



    //更新交易明细表，和库存表
    function  insert_sys_bill($tx_list,$token_sys_user_guid){
        $row=$this->db_select("SELECT guid from token_sys_coin WHERE iscustom=1");
        $token_sys_coin_guid=$row[0]["guid"];
        $sum_tokencount=0;
        $array=array();
        //取最新的一次高度
        $lasttiem=end($tx_list);
        $lastheight=$lasttiem->height+1;
        for ($x=0;$x<count($tx_list);$x++){
           $transaction_id= $tx_list[$x]->txid;
           $sellout_address=$tx_list[$x]->sender;
           $purchasein_address= $tx_list[$x]->receiver;
           $tokencount=$tx_list[$x]->amount;
           $chain_height=$tx_list[$x]->height;
           $sum_tokencount=$sum_tokencount+$tokencount;
           $insertsql="insert into token_bill_transaction_coin (guid,billdate,billdatetime,token_sys_user_guid,sellout_address,tokencount,token_sys_coin_guid,status,type,purchasein_address,transaction_id,chain_height) 
VALUES(UUID(),NOW(),NOW(),'".$token_sys_user_guid."','".$sellout_address."',".$tokencount.",'".$token_sys_coin_guid."',1,0,'".$purchasein_address."','".$transaction_id."',".$chain_height.")";
            $array[]=$insertsql;
        }
        $updatesql="UPDATE token_user_custom_coin_balance set token_count=token_count+".$sum_tokencount." where token_sys_user_guid='".$token_sys_user_guid."'";
        $array[]=$updatesql;

        $update_lastest_height="UPDATE token_user_coin_address set latest_block_height=".$lastheight." where token_sys_user_guid='".$token_sys_user_guid."' and token_sys_coin_guid='".$token_sys_coin_guid."'";
        $array[]=$update_lastest_height;
        $this->db_exec($array);
    }


    ///地址检测
  public  function Custom_ValidateAddress($address){
        $url= $this->Get_Custom_Coin_Url()."/api/validateAddress";
        $data=array("address"=>$address);
        $data= $this->post_json_data($url,json_encode($data));
        $this->checkCustom_Coin($data);
        $result=json_decode($data["result"]);
        return $result->data->validate;
    }


    public function  GetCustom_Coin_address($userid){
       $row= $this->db_select("SELECT address from token_user_coin_address a inner JOIN token_sys_coin b on b.guid=a.token_sys_coin_guid where token_sys_user_guid='".$userid."' and b.iscustom=1");
       $address=$row[0]["address"];
       return $address;
    }

}